from django.db import DatabaseError
from django.shortcuts import render
from django.views import View
from django import http
import json
from essay.models import Essay, Like, Comment, Collect
from user.models import User


# 发表文章
class PublishEssay(View):

    def post(self, request):
        content = json.loads(request.body)['content']
        imgsList = json.loads(request.body)['imgsList']
        phone = json.loads(request.body)['phone']
        spaceId = json.loads(request.body)['spaceId']
        try:
            Essay.objects.create(essay_content=content, space_id=spaceId, phone=phone, essay_images=imgsList)
        except DatabaseError:
            return http.JsonResponse({'code': '206', 'message': '发布失败'})
        return http.JsonResponse({'code': '200', 'message': '发布成功'})


# 获取空间内文章
class GetSpaceEssay(View):

    def get(self, request):
        space_id = request.GET.get('spaceId')
        essay_data = list(Essay.objects.values().filter(space_id=space_id))
        for item in essay_data:
            user_data = list(User.objects.values().filter(phone=item["phone"]))
            query_essay(item, user_data)

        return http.JsonResponse({'code': '200', 'message': '成功', "data": {"essayList": essay_data[::-1]}})


# 删除文章
class DeleteEssay(View):

    def get(self, request):
        essay_id = request.GET.get('essayId')
        Essay.objects.filter(essay_id=essay_id).delete()
        Like.objects.filter(essay_id=essay_id).delete()
        Comment.objects.filter(essay_id=essay_id).delete()
        Collect.objects.filter(essay_id=essay_id).delete()
        return http.JsonResponse({'code': '200', 'message': '删除成功'})


# 点赞
class LikeEssay(View):

    def post(self, request):
        essay_id = json.loads(request.body)['essayId']
        phone = json.loads(request.body)['phone']
        isLike = json.loads(request.body)['isLike']
        like_data = Like.objects.values().filter(essay_id=essay_id, phone=phone)
        if isLike:
            if like_data:
                pass
            else:
                Like.objects.create(essay_id=essay_id, phone=phone)
        else:
            if like_data:
                Like.objects.filter(essay_id=essay_id, phone=phone).delete()
        return http.JsonResponse({'code': '200', 'message': '成功'})


# 评论文章
class CommentEssay(View):

    def post(self, request):
        essay_id = json.loads(request.body)['essayId']
        phone = json.loads(request.body)['phone']
        comment_content = json.loads(request.body)['content']
        target = json.loads(request.body)['target']
        username = json.loads(request.body)['username']
        comment = Comment.objects.create(essay_id=essay_id, phone=phone, comment_content=comment_content,
                               reply_type=target["type"], reply_username=target["username"])
        comment_user = list(User.objects.values().filter(phone=phone))[0]
        response_comment_data = {
            "comment_id": comment.comment_id,
            "comment_content": comment_content,
            "username": comment_user["username"],
            "phone": phone,
            "comment_time": comment.comment_time.strftime("%Y-%m-%d %H:%M:%S"),
            "target": target
        }
        return http.JsonResponse({'code': '200', 'message': '成功', "data": response_comment_data})


# 收藏
class CollectEssay(View):

    def post(self, request):
        essay_id = json.loads(request.body)['essayId']
        phone = json.loads(request.body)['phone']
        isCollect = json.loads(request.body)['isCollect']
        collect_data = Collect.objects.values().filter(essay_id=essay_id, phone=phone)
        if isCollect:
            if collect_data:
                pass
            else:
                Collect.objects.create(essay_id=essay_id, phone=phone)
        else:
            if collect_data:
                Collect.objects.filter(essay_id=essay_id, phone=phone).delete()
        return http.JsonResponse({'code': '200', 'message': '成功'})


# 根据用户id查询用户发布的所有文章
class GetUserEssay(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        phone = list(User.objects.values().filter(user_id=user_id))[0]['phone']
        essay_data = list(Essay.objects.values().filter(phone=phone))
        for item in essay_data:
            user_data = list(User.objects.values().filter(phone=item["phone"]))
            query_essay(item, user_data)

        return http.JsonResponse({'code': '200', 'message': '成功', "data": {"essayList": essay_data[::-1]}})


# 根据用户id查询用户收藏的所有文章
class GetUserCollectEssay(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        phone = list(User.objects.values().filter(user_id=user_id))[0]['phone']
        collect_data = list(Collect.objects.values().filter(phone=phone))
        essay_result_data = []
        for collect in collect_data:
            try:
                essay_data = list(Essay.objects.values().filter(essay_id=collect['essay_id']))[0]
                user_data = list(User.objects.values().filter(phone=essay_data["phone"]))
            except Exception:
                print("数据库异常")
            else:
                query_essay(essay_data, user_data)
                essay_result_data.append(essay_data)
        return http.JsonResponse({'code': '200', 'message': '成功', "data": {"essayList": essay_result_data[::-1]}})


# 查询文章数据并整理方法
def query_essay(essay_data, user_data):
    essay_data["user_id"] = user_data[0]["user_id"]
    essay_data["username"] = user_data[0]["username"]
    essay_data["avatar"] = user_data[0]["avatar"]
    essay_data["images"] = essay_data["essay_images"].split("@")
    essay_data["create_time"] = essay_data["create_time"].strftime("%Y-%m-%d %H:%M:%S")
    essay_data["LikePeople"] = []
    essay_data["comment"] = []
    essay_data["CollectPeople"] = []
    like_data = list(Like.objects.values().filter(essay_id=essay_data["essay_id"]))
    for like in like_data:
        like_user_data = list(User.objects.values().filter(phone=like["phone"]))[0]
        essay_data["LikePeople"].append({
            "user_id": like_user_data["user_id"],
            "lphone": like["phone"],
            "lusername": like_user_data["username"],
            "lavatar": like_user_data["avatar"]
        })
    comment_data = list(Comment.objects.values().filter(essay_id=essay_data["essay_id"]))[::-1]
    for comment in comment_data:
        comment_user_data = list(User.objects.values().filter(phone=comment["phone"]))[0]
        essay_data["comment"].append({
            "user_id": comment_user_data["user_id"],
            "username": comment_user_data["username"],
            "target": {
                "type": comment["reply_type"],
                "username": comment["reply_username"]
            },
            **comment,
            "comment_time": comment["comment_time"].strftime("%Y-%m-%d %H:%M:%S")
        })
    collect_data = list(Collect.objects.values().filter(essay_id=essay_data["essay_id"]))
    for collect in collect_data:
        essay_data["CollectPeople"].append(collect["phone"])
